<template>
  <div class="stats-panel stats-station-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{ $t('report.statistics.title28') }}</h3>
      <div class="stats-form-group">
        <!-- <div id="date-range" class="stats-form-daterange">
          <span>{{timeStart}} - {{timeEnd}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>
    <div class="stats-panel-body">
      <div class="stats-station-chart-wrap" style="width:100%;">
        <div id="event-type-pie"></div>
        <div class="stats-empty" v-if="eventTypeEmpty">{{$t('common.base.tip.noData')}}</div>
      </div>
      <div class="stats-table-wrap" v-if="showTable">
        <div class="stats-table-header">
           <h3>{{ $t('report.stationTable.title2') }}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed">{{ $t('common.base.export') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div>
          <el-table :data="page.list" class="stats-table">
            <el-table-column :label="$t('common.base.serialNumber')" prop="eventNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.eventNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row)">{{scope.row.eventNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="cusName"></el-table-column>
            <el-table-column :label="$t('common.label.eventType')" prop="templateName" width="180px"></el-table-column>
            <el-table-column :label="$t('common.label.principalName')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executorName }}
                </template>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUserName }}
                </template>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';

import http from 'src/util/HttpUtil';
import Loading from 'packages/BaseLoading';
import qs from 'src/util/querystring'
import echarts from 'packages/Echarts';
import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

let EventTypePie = null;
import { t } from '@src/locales';
export default {
  name: 'station-chart',
  data(){
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      timeStart: '',
      timeEnd: '',

      model: {
        pageNum: 1,
        templateName: ''
      },
      eventTypeEmpty: false,
      showTable: false,
      page: {
        list: []
      }
    }
  },
  methods: {
    exportAllData(){
      let model = {}

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;
      
      window.location.href = `/api/report/outside/stats/station/eventCount/exportAll?${ qs.stringify(model)}`;
    },
    exportData(){
      let model = {
        templateName: this.model.templateName
      }

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;
      
      window.location.href = `/api/report/outside/stats/station/eventCount/export?${ qs.stringify(model)}`;
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `eventView_${ row.id}`, 
      //   title: `事件${row.eventNo}`, 
      //   close: true, 
      //   url: `/event/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: row.id,
        titleKey: row.eventNo,
        fromId
      })
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },

    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        pageSize: 10,
        templateName: this.model.templateName
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      return http.post('/api/report/outside/stats/station/eventCount/detail', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);

      try {
        this.page = await this.fetchTableData();
        this.showTable = true;
      } catch (error) {
        console.log(error)
      }

      instance.hide();
    },
    chooseDate(start, end) {
      this.$emit('trackEvent', 'chooseDate');

      this.timeStart = start;
      this.timeEnd = end;
      this.render();
    },
    initChart(start, end){
      EventTypePie = echarts.init(document.getElementById('event-type-pie'));
      
      EventTypePie.on('click', event => {
        this.model.templateName = event.name;
        this.renderTable();
      })
      
      this.timeStart = start;
      this.timeEnd = end;
      this.render();
    },
    async render(){
      try {
        let instance = Loading.show(this.$el);
        let data = await this.fetchEvenCount();
        instance.hide();
        
        this.renderEventTypePie(data.eventType || [])
      } catch (error) {
        console.log(error)
      }
    },
    renderEventTypePie(data){
      this.eventTypeEmpty = false;
      EventTypePie.clear();

      let option = this.getEventTypePieOption(data);
      if(option == null){
        this.eventTypeEmpty = true;
        return
      }

      EventTypePie.setOption(option);
    },
    getEventTypePieOption(data){
      if(data.length == 0) return null;

      let legendData = []
      let seriesData = [];
      data.forEach(item => {
        legendData.push(item.eventType);

        seriesData.push({
          name: item.eventType,
          value: item.eventConut
        })
      })

      return {
        color: ['#2ec7c9', '#ffb980', '#5ab1ef', '#d87a80', '#5f5f6e', '#07a2a4', '#9a7fd1', '#588dd5', '#c05050', '#f5994e', '#59678c', '#7eb00a', '#749f83'],
        tooltip : {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          top: '10px',
          left: 'left',
          orient: 'vertical',
          data: legendData,
          type: 'scroll'
        },
        grid: {
          top: '50px'
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: t('report.statistics.title28')
            }
          },
          right: 40
        },
        series : [
          {
            name: t('common.label.eventType'),
            type: 'pie',
            radius : '55%',
            center: ['50%', '50%'],
            data: seriesData,
            itemStyle: {
              normal: {label : {show: true}},
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              normal: {
                show: true,
                formatter: '{b}： {c} ({d}%)'
              }
            }
          }
        ]
      }
    },
    fetchEvenCount(){
      let params = {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd
      };
      return http.post('/api/report/outside/stats/station/eventCount', params);
    },
    datePicker(data) {
      // 初始化趋势图
      this.initChart(data[0], data[1]);
    }
  },
  mounted(){
    window.addEventListener('resize', _.debounce(function(){
      EventTypePie.resize();
    }, 400))
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>


<style lang="scss">
.stats-station-chart-wrap{
  width: 50%;

  h3{
    margin: 0;
    padding: 15px 0  5px 0;
    text-align: center;
    font-size: 18px;
  }
}

.stats-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}

#event-type-pie{
  height: 420px;
}
</style>
